#!/bin/bash
# 腾讯云服务器快速部署脚本
# 使用方法：将此脚本上传到服务器后执行 bash 快速部署脚本.sh

set -e

echo "======================================"
echo "问卷系统自动部署脚本"
echo "======================================"
echo ""

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}请使用root权限运行此脚本${NC}"
    echo "执行: sudo bash 快速部署脚本.sh"
    exit 1
fi

# 变量配置
PROJECT_NAME="审计"
PROJECT_DIR="/var/www/${PROJECT_NAME}"
VENV_DIR="${PROJECT_DIR}/backend/venv"
BACKEND_SERVICE="survey-backend"

# 获取服务器IP
SERVER_IP=$(curl -s ifconfig.me)
echo -e "${GREEN}检测到服务器IP: ${SERVER_IP}${NC}"
echo ""

# 1. 更新系统
echo "[1/8] 更新系统..."
apt update && apt upgrade -y

# 2. 安装Python 3.11
echo "[2/8] 安装Python 3.11..."
apt install -y software-properties-common
add-apt-repository ppa:deadsnakes/ppa -y
apt update
apt install -y python3.11 python3.11-venv python3.11-dev python3-pip

# 3. 安装Node.js
echo "[3/8] 安装Node.js 18..."
curl -fsSL https://deb.nodesource.com/setup_18.x | bash -
apt install -y nodejs

# 4. 安装Nginx
echo "[4/8] 安装Nginx..."
apt install -y nginx

# 5. 配置后端
echo "[5/8] 配置Django后端..."
cd ${PROJECT_DIR}/backend

# 创建虚拟环境
python3.11 -m venv venv
source venv/bin/activate

# 安装依赖
pip install --upgrade pip
pip install django djangorestframework django-cors-headers gunicorn

# 执行迁移
python manage.py migrate
python manage.py collectstatic --noinput

# 6. 配置Gunicorn服务
echo "[6/8] 配置Gunicorn服务..."
cat > /etc/systemd/system/${BACKEND_SERVICE}.service << EOF
[Unit]
Description=Survey Django Backend
After=network.target

[Service]
User=root
Group=www-data
WorkingDirectory=${PROJECT_DIR}/backend
Environment="PATH=${VENV_DIR}/bin"
ExecStart=${VENV_DIR}/bin/gunicorn \\
          --workers 3 \\
          --bind 127.0.0.1:8000 \\
          config.wsgi:application

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl start ${BACKEND_SERVICE}
systemctl enable ${BACKEND_SERVICE}

# 7. 构建前端
echo "[7/8] 构建前端..."
cd ${PROJECT_DIR}/frontend
npm install
npm run build

# 8. 配置Nginx
echo "[8/8] 配置Nginx..."
cat > /etc/nginx/sites-available/survey << EOF
server {
    listen 80;
    server_name ${SERVER_IP};

    location / {
        root ${PROJECT_DIR}/frontend/dist;
        try_files \$uri \$uri/ /index.html;
        index index.html;
    }

    location /api/ {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }

    location /static/ {
        alias ${PROJECT_DIR}/backend/staticfiles/;
    }
}
EOF

ln -sf /etc/nginx/sites-available/survey /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default
nginx -t
systemctl restart nginx

# 配置防火墙
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable

echo ""
echo "======================================"
echo -e "${GREEN}部署完成！${NC}"
echo "======================================"
echo ""
echo "访问地址: http://${SERVER_IP}"
echo ""
echo "常用命令:"
echo "  查看后端日志: journalctl -u ${BACKEND_SERVICE} -f"
echo "  重启后端: systemctl restart ${BACKEND_SERVICE}"
echo "  重启Nginx: systemctl restart nginx"
echo ""
echo "后续建议:"
echo "  1. 配置域名和HTTPS证书"
echo "  2. 修改settings.py中的SECRET_KEY"
echo "  3. 定期备份数据库文件"
echo "======================================"
